/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ronsicecream.pos.wh.transaction.returtosupplier;

import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Controller;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Sequence;
import com.buanalintas.bynga.Utility;
import com.ronsicecream.pos.entities.PosMasterItemStock;
import com.ronsicecream.pos.entities.PosMasterStatus;
import com.ronsicecream.pos.entities.PosTransactionHoReceiptFromSupplier;
import com.ronsicecream.pos.entities.PosTransactionHoReturToSupplier;
import com.ronsicecream.pos.entities.PosTransactionHoReturToSupplierDetail;
import com.ronsicecream.pos.entities.PosTransactionItemStock;
import com.ronsicecream.pos.master.item.Item;
import com.ronsicecream.pos.master.status.Status;
import com.ronsicecream.pos.wh.transaction.returtosupplierdetail.ReturToSupplierDetail;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import javax.persistence.EntityManager;

/**
 *
 * @author user
 */
public class ReturToSupplier extends Page {

    private Field returId;
    private Field returDate;
    private Field returNumber;
    private Field returQuantity;
    private Field returDescription;
    private Field returTimestamp;
    private Field returReceiptId;
    private Field returSupplierId;
    private Field returRegionalId;
    private Field returUnitId;
    private Field returUserId;

    public ReturToSupplier() {
        super();

        setTheClass(PosTransactionHoReturToSupplier.class);

        setPageDetail(ReturToSupplierDetail.class);


        returId = new Field();
        returId.setName("returId");
        returId.setCaption("id");
        //returId.setInfo("retur id");
        returId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        returId.setInputProperties(" size=\"20\"");
        getFields().add(returId);

        returDate = new Field();
        returDate.setName("returDate");
        returDate.setCaption("date");
        returDate.setRequired(true);
        returDate.setListProperties(" align=\"center\" width=\"5%\" nowrap");
        returDate.setInputProperties(" size=\"8\"");
//        returDate.setFormatter(DateFormatter.getInstanceDate(this));
        getFields().add(returDate);

        returNumber = new Field();
        returNumber.setName("returNumber");
        returNumber.setCaption("number");
        returNumber.setRequired(true);
        returNumber.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        returNumber.setInputProperties(" size=\"30\" readonly");
        getFields().add(returNumber);

        returQuantity = new Field();
        returQuantity.setName("returQuantity");
        returQuantity.setCaption("quantity");
        //returQuantity.setInfo("retur quantity");
        returQuantity.setListProperties(" align=\"left\" width=\"5%\" nowrap");
        returQuantity.setInputProperties(" size=\"20\"");
        getFields().add(returQuantity);

        returDescription = new Field();
        returDescription.setName("returDescription");
        returDescription.setCaption("description");
        //returDescription.setInfo("retur description");
        returDescription.setListProperties(" align=\"left\" width=\"35%\" nowrap");
        returDescription.setListProperties(" align=\"left\" width=\"60%\" nowrap");
        returDescription.setInputProperties(" cols=\"50\" rows=\"5\"");
        returDescription.setInputType(Field.INPUT_TEXT_AREA);
        returDescription.setInputCase(Field.CASE_UPPER);
        getFields().add(returDescription);

        returTimestamp = new Field();
        returTimestamp.setName("returTimestamp");
        returTimestamp.setCaption("timestamp");
        //returTimestamp.setInfo("retur timestamp");
        returTimestamp.setListProperties(" align=\"center\" width=\"10%\" nowrap");
        returTimestamp.setInputProperties(" size=\"12\"");
//        returTimestamp.setFormatter(DateFormatter.getInstanceDateTime(this));
        returTimestamp.setDefaultValue(Utility.getTimestamp());
        getFields().add(returTimestamp);

        returReceiptId = new Field();
        returReceiptId.setName("returReceiptId");
        returReceiptId.setCaption("receipt");
        returReceiptId.setRequired(true);
        returReceiptId.setListProperties(" align=\"left\" width=\"15%\" nowrap");
        returReceiptId.setInputProperties(" size=\"20\"");
        returReceiptId.setSelectorLoad(true);
        returReceiptId.setSelectorCondition("t.receiptKeel='1'");
        returReceiptId.getSelectorColumns().add(new String[]{"receiptNumber", "Number", " align=\"center\" width=\"20%\" nowrap"});
        returReceiptId.getSelectorColumns().add(new String[]{"receiptTotal", " Total ", "align=\"right\" width=\"10%\""});
        returReceiptId.getSelectorColumns().add(new String[]{"receiptQuantity", " Quantity", " align=\"center\" width=\"10%\" nowrap"});
        returReceiptId.getSelectorColumns().add(new String[]{"receiptDescription", " Description", "align=\"left\" width=\"60%\""});
        returReceiptId.setSelectorOrder("t.receiptNumber");
        getFields().add(returReceiptId);

        returSupplierId = new Field();
        returSupplierId.setName("returSupplierId");
        returSupplierId.setCaption("supplier");
        //posMasterSupplier.setInfo("pos master supplier");
        returSupplierId.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        returSupplierId.setInputProperties(" size=\"20\"");
        getFields().add(returSupplierId);

        returRegionalId = new Field();
        returRegionalId.setName("returRegionalId");
        returRegionalId.setCaption("regional");
        //posMasterRegional.setInfo("pos master regional");
        returRegionalId.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        returRegionalId.setInputProperties(" size=\"20\"");
        getFields().add(returRegionalId);

        returUnitId = new Field();
        returUnitId.setName("returUnitId");
        returUnitId.setCaption("unit");
        //posMasterRegional.setInfo("pos master regional");
        returUnitId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        returUnitId.setInputProperties(" size=\"20\"");
        getFields().add(returUnitId);

        returUserId = new Field();
        returUserId.setName("returUserId");
        returUserId.setCaption("user");
        //posMasterRegional.setInfo("pos master regional");
        returUserId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        returUserId.setInputProperties(" size=\"20\"");
        getFields().add(returUserId);

        getActions().add(Action.TRANS_ADD);
        getActions().add(Action.TRANS_EDIT);
        getActions().add(Action.TRANS_VIEW);

        fillFields();

        getFieldsAdd().clear();
        getFieldsAdd().add(returNumber);
        getFieldsAdd().add(returReceiptId);
//        getFieldsAdd().add(returRegionalId);
        getFieldsAdd().add(returDescription);

        getFieldsEdit().clear();
        getFieldsEdit().add(returNumber);
        getFieldsEdit().add(returReceiptId);
//        getFieldsEdit().add(returRegionalId);
        getFieldsEdit().add(returDescription);

        getFieldsList().clear();
        getFieldsList().add(returNumber);
        getFieldsList().add(returReceiptId);
        getFieldsList().add(returRegionalId);
        getFieldsList().add(returDate);
        getFieldsList().add(returQuantity);
        getFieldsList().add(returSupplierId);
        getFieldsList().add(returDescription);

        getFieldsView().clear();
        getFieldsView().add(returDate);
        getFieldsView().add(returNumber);
        getFieldsView().add(returQuantity);
        getFieldsView().add(returReceiptId);
        getFieldsView().add(returSupplierId);
        getFieldsView().add(returTimestamp);
        getFieldsView().add(returDescription);

        setController(new ReturToSupplier.ReturController(this));

        setExportList(getClass().getResourceAsStream("ReturToSupplierList.jasper"));
        setExport(getClass().getResourceAsStream("ReturToSupplier.jasper"));

    }

    class ReturController extends Controller {

        public ReturController(Page page) {
            super(page);
            setOrder(returTimestamp);
            setOrderType("DESC");
        }

        @Override
        public void beforeInsert(Object data, List list) {
            PosTransactionHoReturToSupplier retur = (PosTransactionHoReturToSupplier) data;
            EntityManager em = getEntityManager();
            retur.setReturNumber(generate());
            retur.setReturUnitId(getCurrentUnit());
            retur.setReturUserId(getCurrentUser());
            retur.setReturTimestamp(Utility.getTimestamp());
            retur.setReturDate(Utility.getTimestamp());
            PosTransactionHoReceiptFromSupplier receipt = retur.getReturReceiptId();
            retur.setReturSupplierId(receipt.getReceiptSupplierId());
            System.out.println("retur s:" + retur.getReturSupplierId());
//            retur.setReturRegionalId(receipt.getReceiptRegionalId());
//            System.out.println("retur r:" + retur.getReturRegionalId());

        }

        @Override
        public void afterInsert(Object data, List list) {

            EntityManager em = getEntityManager();
            PosMasterStatus statusGood = Status.getStatusGood(em);
            try {
                em.getTransaction().begin();
                PosTransactionHoReturToSupplier retur = (PosTransactionHoReturToSupplier) data;
                PosTransactionHoReceiptFromSupplier receipt = retur.getReturReceiptId();
                retur.setReturPosUnitId(receipt.getReceiptPosUnitId());
                System.out.println("retur s:" + retur.getReturPosUnitId());
                retur.setReturRegionalId(receipt.getReceiptRegionalId());
                System.out.println("retur r:" + retur.getReturRegionalId());
                BigDecimal total = BigDecimal.ZERO;
                BigDecimal totalQuantity = BigDecimal.ZERO;
                String desc = " ";
                for (Object detail : list) {
                    PosTransactionHoReturToSupplierDetail returDetail = (PosTransactionHoReturToSupplierDetail) detail;


                    PosMasterItemStock stock = Item.getStockItem(em, returDetail.getReturDetailItemId(), retur.getReturUnitId());
                    PosTransactionItemStock itemStock = new PosTransactionItemStock();

                    itemStock.setItemStockId(Sequence.next(itemStock));
                    itemStock.setItemStockItemId(returDetail.getReturDetailItemId());
                    itemStock.setItemStockUnitId(retur.getReturUnitId());
                    itemStock.setItemStockStatusId(statusGood);
                    itemStock.setItemStockType("2");
//                    itemStock.setItemStockRegionalId(retur.getReturRegionalId());
//                    itemStock.setItemStockPosUnitId(retur.getReturPosUnitId());
                    itemStock.setItemStockLast(stock.getItemStockValue());
                    itemStock.setItemStockValue(returDetail.getReturDetailQuantity());
                    itemStock.setItemStockCurrent(stock.getItemStockValue().subtract(itemStock.getItemStockValue()));
                    itemStock.setItemStockUserId(getCurrentUser());
                    itemStock.setItemStockTimestamp(Utility.getTimestamp());
                    System.out.println(itemStock.getItemStockId() + "<<=========dedy=");
                    em.persist(itemStock);
                    stock.setItemStockValue(itemStock.getItemStockCurrent());
                    total = total.add(returDetail.getReturDetailPrice().multiply(returDetail.getReturDetailQuantity()));
                    totalQuantity = totalQuantity.add(returDetail.getReturDetailQuantity());

                    desc = desc + "Retur " + returDetail.getReturDetailItemId() + " Quantity = " + returDetail.getReturDetailQuantity()
                            //                            + " Dengan Harga = " + returDetail.getReturDetailPrice()
                            + ". ";
                }
                System.out.println("total :" + total);
                System.out.println("total qty :" + totalQuantity);
                System.out.println("desc :" + desc);

//                    retur.setReceiptTotal(total);
                retur.setReturDescription(desc);
                retur.getReturReceiptId().setReceiptDescription(desc);
                retur.getReturReceiptId().setReceiptUnpaid(receipt.getReceiptUnpaid().subtract(total));
                retur.setReturQuantity(totalQuantity);
                em.getTransaction().commit();
            } catch (Exception e) {
                System.out.println("errorrr :" + e);
            }
        }
    }

    @Override
    public void beforeAdd() {
        returNumber.setDefaultValue(generate());
    }

    public String generate() {
        String unitCode = (getCurrentUnit()).getUnitCode();
        Calendar cal = Calendar.getInstance();
        String year = "" + cal.get(Calendar.YEAR);
        String month = Utility.intToRoman(cal.get(Calendar.MONTH) + 1);
        try {
            PosTransactionHoReturToSupplier ret = (PosTransactionHoReturToSupplier) getEntityManager().createQuery("SELECT t FROM PosTransactionHoReturToSupplier t "
                    + "WHERE t.returNumber LIKE '%/" + unitCode + "/Rons/RET-Supplier/%/" + year + "' "
                    + "ORDER BY t.returTimestamp DESC").setHint(Persistence.REFRESH_HINT, true).setFirstResult(0).setMaxResults(1).getSingleResult();
            return Utility.lpad(Integer.parseInt(ret.getReturNumber().substring(0, 4)) + 1, 4, "0") + "/" + unitCode + "/Rons/RET-Supplier/" + month + "/" + year;
        } catch (Exception e) {
        }
        return "0001/" + unitCode + "/Rons/RT-Supplier/" + month + "/" + year;
    }
}
